﻿namespace OboutInc.ImageZoom
{
    using OboutInc.ImageZoom.Encryption;
    using OboutInc.ImageZoom.ImageFactory;
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Net;
    using System.Runtime.CompilerServices;
    using System.Web;

    internal class ImageZoomImageFactory
    {
        private string _cachedPath = string.Empty;
        private string _cacheKey = "";
        private string _customCacheFolder = string.Empty;
        private bool _enableDiskCaching;
        private int _height;
        private string _imageDir = string.Empty;
        private string[] _imageName;
        private string _imagePath = string.Empty;
        private bool _isBig;
        private bool _isStream;
        private string[] _paramList;
        private string _virtualPath = string.Empty;
        private Color _waterMarkColor = Color.WhiteSmoke;
        private string _waterMarkFontFamily = "verdana";
        private int _waterMarkFontSize = 12;
        private FontStyle _waterMarkFontStyle = FontStyle.Bold;
        private string _waterMarkText = "";
        private int _width;
        private Bitmap obImage;

        internal void Draw()
        {
            if (this.IzhttpContext.Request.Params["oboutizf"] == null)
            {
                this.IzhttpContext.Response.End();
            }
            try
            {
                this._virtualPath = this.IzhttpContext.Request.Params["oboutizf"];
                this._paramList = OboutInc.ImageZoom.Encryption.Encryption.Base64Decode(this._virtualPath).Split(new char[] { '&' });
                string path = OboutInc.ImageZoom.Encryption.Encryption.Base64Decode(this._paramList[0].Substring(2));
                this._virtualPath = path;
                this._imageName = path.Split(new char[] { '/' });
                if (path.StartsWith("http://") || path.StartsWith("https://"))
                {
                    this._imagePath = path;
                }
                else
                {
                    this._imagePath = this.IzhttpContext.Server.MapPath(path);
                }
                this._height = int.Parse(this._paramList[1].Split(new char[] { '=' })[1]);
                this._width = int.Parse(this._paramList[2].Split(new char[] { '=' })[1]);
                this._enableDiskCaching = Convert.ToBoolean(this._paramList[3].Split(new char[] { '=' })[1]);
                this._isBig = Convert.ToBoolean(this._paramList[4].Split(new char[] { '=' })[1]);
                this._waterMarkText = this._paramList[5].Split(new char[] { '=' })[1];
                this._customCacheFolder = this._paramList[6].Split(new char[] { '=' })[1];
                if (this._paramList.Length > 7)
                {
                    this._cacheKey = this._paramList[7].Split(new char[] { '=' })[1];
                    this._isStream = Convert.ToBoolean(this._paramList[8].Split(new char[] { '=' })[1]);
                    this._waterMarkColor = Color.FromName(this._paramList[9].Split(new char[] { '=' })[1]);
                    this._waterMarkFontFamily = this._paramList[10].Split(new char[] { '=' })[1];
                    this._waterMarkFontSize = int.Parse(this._paramList[11].Split(new char[] { '=' })[1]);
                    string str3 = this._paramList[12].Split(new char[] { '=' })[1].ToLower();
                    if (str3 != null)
                    {
                        if (!(str3 == "bold"))
                        {
                            if (str3 == "italic")
                            {
                                goto Label_032B;
                            }
                            if (str3 == "regular")
                            {
                                goto Label_0334;
                            }
                            if (str3 == "strikeout")
                            {
                                goto Label_033D;
                            }
                            if (str3 == "underline")
                            {
                                goto Label_0346;
                            }
                        }
                        else
                        {
                            this._waterMarkFontStyle = FontStyle.Bold;
                        }
                    }
                }
                goto Label_0357;
            Label_032B:
                this._waterMarkFontStyle = FontStyle.Italic;
                goto Label_0357;
            Label_0334:
                this._waterMarkFontStyle = FontStyle.Regular;
                goto Label_0357;
            Label_033D:
                this._waterMarkFontStyle = FontStyle.Strikeout;
                goto Label_0357;
            Label_0346:
                this._waterMarkFontStyle = FontStyle.Underline;
            }
            catch (Exception exception1)
            {
                if (exception1 != null)
                {
                }
            }
        Label_0357:
            this.IzhttpContext.Response.Clear();
            if (!string.IsNullOrEmpty(this._imagePath))
            {
                this.IzhttpContext.Response.ContentType = GetContentType(this._imagePath);
                if (this._imagePath.StartsWith("http://") || this._imagePath.StartsWith("https://"))
                {
                    Stream stream = new WebClient().OpenRead(this._imagePath);
                    this.obImage = new Bitmap(stream);
                }
                else
                {
                    this.obImage = new Bitmap(this._imagePath);
                }
            }
            else if (this._isStream)
            {
                this.IzhttpContext.Response.ContentType = "image/jpeg";
                byte[] buffer = this.IzhttpContext.Cache[this._cacheKey] as byte[];
                MemoryStream stream2 = new MemoryStream(buffer);
                this.obImage = new Bitmap(stream2);
                this.IzhttpContext.Cache.Remove(this._cacheKey);
            }
            if (!string.IsNullOrEmpty(this._waterMarkText) && (this._width == 0))
            {
                ImageZoomWaterMark mark = new ImageZoomWaterMark(this.obImage, this._waterMarkText);
                mark.AddWatermark();
                mark.Image.Save(this.IzhttpContext.Response.OutputStream, GetImageFormat(this._imagePath));
                this.IzhttpContext.Response.End();
            }
            if (this._enableDiskCaching)
            {
                this.SetCachePath();
            }
            if ((this._width <= 0) && (this._height <= 0))
            {
                this.IzhttpContext.Response.Clear();
                this.IzhttpContext.Response.ContentType = GetContentType(this._imagePath);
                this.IzhttpContext.Response.WriteFile(this._imagePath);
                this.IzhttpContext.Response.End();
            }
            if (System.IO.File.Exists(this._cachedPath))
            {
                this.IzhttpContext.Response.Clear();
                OutputCacheResponse(this.IzhttpContext, System.IO.File.GetLastWriteTime(this._cachedPath));
                this.IzhttpContext.Response.WriteFile(this._cachedPath);
                this.IzhttpContext.Response.End();
            }
            try
            {
                MemoryStream stream3 = null;
                if (string.IsNullOrEmpty(this._waterMarkText))
                {
                    stream3 = new ImageZoomResize().GetResizedImage(this.obImage, this._width, this._height, ImageFormat.Jpeg);
                }
                else
                {
                    stream3 = new ImageZoomResize().GetResizedImageWithWaterMark(this.obImage, this._width, this._height, ImageFormat.Jpeg, this._waterMarkText, this._isBig, this._waterMarkColor, this._waterMarkFontFamily, this._waterMarkFontSize, this._waterMarkFontStyle);
                }
                stream3.WriteTo(this.IzhttpContext.Response.OutputStream);
                if (!this._imagePath.StartsWith("http://") && !this._imagePath.StartsWith("https://"))
                {
                    OutputCacheResponse(this.IzhttpContext, System.IO.File.GetLastWriteTime(this._imagePath));
                }
                using (FileStream stream4 = new FileStream(this._cachedPath, FileMode.CreateNew))
                {
                    stream3.WriteTo(stream4);
                }
                stream3.Dispose();
            }
            catch (Exception exception2)
            {
                if (exception2.Message != null)
                {
                    exception2 = null;
                }
            }
            this.IzhttpContext.Response.End();
        }

        internal static string GetContentType(string path)
        {
            switch (Path.GetExtension(path))
            {
                case ".bmp":
                    return "Image/bmp";

                case ".gif":
                    return "Image/gif";

                case ".jpg":
                    return "Image/jpeg";

                case ".png":
                    return "Image/png";
            }
            return "";
        }

        internal static ImageFormat GetImageFormat(string path)
        {
            switch (Path.GetExtension(path))
            {
                case ".bmp":
                    return ImageFormat.Bmp;

                case ".gif":
                    return ImageFormat.Gif;

                case ".jpg":
                    return ImageFormat.Jpeg;

                case ".png":
                    return ImageFormat.Png;
            }
            return ImageFormat.Jpeg;
        }

        private static void OutputCacheResponse(HttpContext context, DateTime lastModified)
        {
            HttpCachePolicy cache = context.Response.Cache;
            cache.SetCacheability(HttpCacheability.Public);
            cache.VaryByParams["oboutizf"] = true;
            cache.VaryByParams["h"] = true;
            cache.VaryByParams["w"] = true;
            cache.SetOmitVaryStar(true);
            cache.SetExpires(DateTime.Now + TimeSpan.FromDays(30.0));
            cache.SetValidUntilExpires(true);
            cache.SetLastModified(lastModified);
        }

        private void SetCachePath()
        {
            try
            {
                if (this._customCacheFolder != string.Empty)
                {
                    this._imageDir = this._customCacheFolder;
                }
                else if (this._virtualPath != null)
                {
                    this._imageDir = this._virtualPath.Substring(0, this._virtualPath.LastIndexOf('/'));
                }
                if (this._imageDir != null)
                {
                    this._cachedPath = this.IzhttpContext.Server.MapPath(string.Concat(new object[] { this._imageDir, "/IZ_cache/", this._width, this._height, this._imageName[this._imageName.Length - 1] }));
                }
                else if (HttpRuntime.CodegenDir != null)
                {
                    this._cachedPath = Path.Combine(HttpRuntime.CodegenDir, (this._width + this._height) + this._imageName[this._imageName.Length - 1]);
                }
            }
            catch (Exception exception1)
            {
                if (exception1 != null)
                {
                }
            }
        }

        public string IImageUrl { get; set; }

        public HttpContext IzhttpContext { get; set; }
    }
}

